package com.gaussic.filter;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/31 0031.
 */
public class EncodingFilter implements Filter {


    private FilterConfig filterConfig = null;
    private String defaultCharset = "UTF-8";

    // 项目结束时就已经进行销毁
    public void destroy() {
        System.out.println("end do the encoding filter!");
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //得到在web.xml中配置的字符编码
        String charset = filterConfig.getInitParameter("charset");
        System.out.println("before encoding  filter！");
        if(charset==null){
            charset = defaultCharset;
        }
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);
        response.setContentType("text/html;charset="+charset);

        MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request);
        chain.doFilter(requestWrapper, response);

        //chain.doFilter(req, resp);
        System.out.println("after encoding  filter！");
        System.err.println("------------------8888----------------------");
    }

    // 项目启动时就已经进行读取
    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
        System.out.println("begin do the encoding filter!");
    }
}